package com.hubei.car.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis分布式锁
 * @author luokangtao
 * @create 2019-07-31 18:34
 */
@Component
public class RedisLockUtil {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 加锁
     * @param key redis key
     * @param expire 过期时间，单位秒
     * @return true:加锁成功，false，加锁失败
     */
    public  boolean lock(String key, int expire, TimeUnit unit) {
        if(!redisTemplate.hasKey(key)) {
            redisTemplate.boundValueOps(key).set(key,expire,unit);
            return true;
        }
        return false;
    }

    /**
     * 释放锁
     * @param key
     */
    public void unLock(String key) {
        redisTemplate.delete(key);
    }

}
